<?php
declare(strict_types=1);
 

namespace App\Fastapp\Mapper;

use App\Fastapp\Model\FastappAd;
use App\Fastapp\Model\FastappAdPosition;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 广告位列表Mapper类
 */
class FastappAdPositionMapper extends AbstractMapper
{
    /**
     * @var FastappAdPosition
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappAdPosition::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {

        // 主键
        if (isset($params['id']) && filled($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 创建时间
        if (isset($params['created_at']) && filled($params['created_at']) && is_array($params['created_at']) && count($params['created_at']) == 2) {
            $query->whereBetween(
                'created_at',
                [$params['created_at'][0], $params['created_at'][1]]
            );
        }

        // 更新时间
        if (isset($params['updated_at']) && filled($params['updated_at']) && is_array($params['updated_at']) && count($params['updated_at']) == 2) {
            $query->whereBetween(
                'updated_at',
                [$params['updated_at'][0], $params['updated_at'][1]]
            );
        }

        // 删除时间
        if (isset($params['deleted_at']) && filled($params['deleted_at']) && is_array($params['deleted_at']) && count($params['deleted_at']) == 2) {
            $query->whereBetween(
                'deleted_at',
                [$params['deleted_at'][0], $params['deleted_at'][1]]
            );
        }

        // 位置名称
        if (isset($params['name']) && filled($params['name'])) {
            $query->where('name', 'like', '%' . $params['name'] . '%');
        }

        // 投放广告
        if (isset($params['ad_id']) && filled($params['ad_id'])) {
            $query->where('ad_id', '=', $params['ad_id']);
        }

        // 调用代码
        if (isset($params['code']) && filled($params['code'])) {
            $query->where('code', '=', $params['code']);
        }

        return $query;
    }

    public function getPageList(?array $params, bool $isScope = true, string $pageName = 'page'): array
    {
        $res = parent::getPageList($params, $isScope);

        if ($res['items']) {
            $ads = FastappAd::query()->pluck('name', 'id')->toArray();
            foreach ($res['items'] as $item) {
                $ad = [];
                foreach ($item->ad_id ?: [] as $aid) {
                    if (isset($ads[$aid])) $ad[] = $ads[$aid];
                }
                $item->ads = implode($ad);
            }

        }
        return $res;
    }
}